
const axios = require('axios');
const cheerio = require('cheerio');
const fs = require('fs');
const path = require('path');
async function fetchImages(url) {
  try {
    const { data } = await axios.get(url);
   
    const $ = cheerio.load(data);
    const images = $('img')
      .map((i, img) => $(img).attr('src').split('?')[0]+'?w=100')
      .get()
      .filter(src => src.startsWith('https')); // 确保是绝对路径




    let imageCount = 0;
    for (const imageSrc of images) {
      const response = await axios({
        url: imageSrc,
        responseType: 'stream',
      });
      const filename = `image-${++imageCount}.jpg`;
      const filePath = path.join(__dirname, `./imgs2/${filename}`);
      response.data.pipe(fs.createWriteStream(filePath));
      await new Promise((resolve, reject) => {
        response.data.on('error', reject);
        response.data.on('end', resolve);
      });
    }
    console.log(`Downloaded ${imageCount} images.`);
  } catch (error) {
    console.error('An error occurred:', error);
  }
}

// 使用例子
const url = 'https://tactics.tools/info/set-12/tables/thiefs-gloves'; // 替换为你想爬取图片的网页地址
fetchImages(url);
